package edu.byu.intex2.data.dao;

import edu.byu.intex2.data.Cache;
import edu.byu.intex2.data.ConnectionPool;
import edu.byu.intex2.data.DataException;
import edu.byu.intex2.data.GUID;
import edu.byu.intex2.data.bo.PartsAtServiceFacility;
import java.sql.*;

/**
 * PartsAtServiceFacility Data Access Object
 * @author Brady
 */
public class PartsAtServiceFacilityDAO {

    /////////////////////////////////////////////
    ///   Singleton code
    private static PartsAtServiceFacilityDAO instance = null;

    /** Creates a new instance of PartsAtServiceFacilityDAO */
    private PartsAtServiceFacilityDAO() {
    }//constructor

    /** Retrieves the single instance of this class */
    public static synchronized PartsAtServiceFacilityDAO getInstance() {
        if (instance == null) {
            instance = new PartsAtServiceFacilityDAO();
        }
        return instance;
    }//getInstance

    ////////////////////////////////////////////
    ///   CREATE methods
    /**
     * Creates a new partsAtServiceFacility in the database
     * @param id GUID
     * @param partId id of part
     */
    public PartsAtServiceFacility create(String serviceFacilityId, String partId) throws DataException {
        PartsAtServiceFacility partsAtServiceFacility = new PartsAtServiceFacility(GUID.generate()); // generate a guid even though we never use this...
        partsAtServiceFacility.setObjectAlreadyInDB(false);

        // Set ServiceFacility ID
        partsAtServiceFacility.setServiceFacilityId(serviceFacilityId);

        // Set Part
        partsAtServiceFacility.setPartId(partId);

        Cache.getInstance().put(partsAtServiceFacility.getId(), partsAtServiceFacility); // put in cache just in case...
        return partsAtServiceFacility;
    }//create


    ////////////////////////////////////////////
    ///   READ methods
    /**
     * Reads an existing partsAtServiceFacility from the database     */
    public PartsAtServiceFacility read(String serviceFacilityId, String partId) throws DataException {
        // Check Cache -- can't with an partsAtServiceFacility
//        if (Cache.getInstance().containsKey(id)) {
//            return (PartsAtServiceFacility) Cache.getInstance().get(id);
//        }

        // Get Connection
        Connection conn = ConnectionPool.getInstance().get();

        // Try Reading with connection
        try {
            return read(serviceFacilityId, partId, conn);
        } catch (Exception e) {
            throw new DataException("An error occurred while reading the PartsAtServiceFacility object information.", e);
        } finally {
            ConnectionPool.getInstance().release(conn);
        }
    }

    /**
     * Internal method to read an existing partsAtServiceFacility from the database
     * @return partsAtServiceFacility
     */
    synchronized PartsAtServiceFacility read(String serviceFacilityId, String partId, Connection conn) throws Exception {
        // Check Cache
//        if (Cache.getInstance().containsKey(serviceFacilityId)) {
//            return (PartsAtServiceFacility) Cache.getInstance().get(serviceFacilityId);
//        }

        // Prepare a SQL Statement
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM parts_at_service_facility where service_facility_id=? AND part_id=?");

        try {
            stmt.setString(1, serviceFacilityId);
            stmt.setString(2, partId);
            ResultSet rs = stmt.executeQuery(); // execute query
            if (rs.next()) {
                // Read the record with the result set
                return readRecord(rs, conn);
            }//if
            throw new DataException("PartsAtServiceFacility with serviceFacilityId '" + serviceFacilityId + "' not found.");
        } finally {
            stmt.close();
        }
    }//read

    /** Internal method to create a partsAtServiceFacility object from a record  */
    synchronized PartsAtServiceFacility readRecord(ResultSet rs, Connection conn) throws Exception {
        if (Cache.getInstance().containsKey(rs.getString("id"))) {
            return (PartsAtServiceFacility) Cache.getInstance().get(rs.getString("id"));
        }
        // Create new partsAtServiceFacility object
        PartsAtServiceFacility partsAtServiceFacility = new PartsAtServiceFacility(rs.getString("id"));

        // PartsAtServiceFacility is already in DB
        partsAtServiceFacility.setObjectAlreadyInDB(true);

        // Put partsAtServiceFacility in cache
        Cache.getInstance().put(partsAtServiceFacility.getId(), partsAtServiceFacility);

        // Set PartsAtServiceFacility Attributes
        // TODO: Assign Correct PartsAtServiceFacility Attributes
        //      Date: 3/4/2009 - Brady White
        partsAtServiceFacility.setServiceFacilityId(rs.getString("serviceFacility_id"));
        partsAtServiceFacility.setPartId(rs.getString("physical_car_id"));
//        partsAtServiceFacility.setActualPrice(rs.getDouble("actual_price"));
//        partsAtServiceFacility.setListPrice(rs.getDouble("list_price"));

        // PartsAtServiceFacility is dirty and needs to be saved to DB
        partsAtServiceFacility.setDirty(false);

        return partsAtServiceFacility;
    }//readRecord


    /////////////////////////////////////////////
    ///   UPDATE methods
    /** Saves an existing partsAtServiceFacility in the database */
    public void save(PartsAtServiceFacility partsAtServiceFacility) throws DataException {
        // get a connection from the pool, save all of the serviceFacilitys first using the other partsAtServiceFacility method and then commit them in the database
        Connection conn = ConnectionPool.getInstance().get();

        try {
            save(partsAtServiceFacility, conn); // save with connection
            conn.commit();  // commit the db transaction
        } catch (Exception e) {
            try {
                //rollback if there were any errors saving, catch any other errors you might have
                conn.rollback();
            } catch (SQLException e2) {
                throw new DataException("Could not roll back the partsAtServiceFacility database transaction!", e2);
            }
            throw new DataException("An error occurred while saving the partsAtServiceFacility object information.", e);
        } finally {
            // release the connection
            ConnectionPool.getInstance().release(conn);
        }
    }

    /** Internal method to update a partsAtServiceFacility in the database */
    void save(PartsAtServiceFacility partsAtServiceFacility, Connection conn) throws Exception {
        // put the partsAtServiceFacility object to cache
        Cache.getInstance().put(partsAtServiceFacility.getId(), partsAtServiceFacility);

        // decide whether to update or insert into the database
        if (partsAtServiceFacility.isObjectAlreadyInDB() && partsAtServiceFacility.isDirty()) {
            update(partsAtServiceFacility, conn);
        } else if (partsAtServiceFacility.isDirty()) {
            insert(partsAtServiceFacility, conn);
        }//if
    }

    /** External method to update or create a partsAtServiceFacility in the database without committing connection */
    public void saveNoCommit(PartsAtServiceFacility partsAtServiceFacility, Connection conn) throws Exception {
        // Get Already in Databsae
         Boolean alreadyInDB = partsAtServiceFacility.isObjectAlreadyInDB();

        // decide whether to update or insert into the database
        if (alreadyInDB) {
            update(partsAtServiceFacility, conn);
        } else {
            insert(partsAtServiceFacility, conn);
        }

        // Save No Commit our pretty part
        PartDAO.getInstance().saveNoCommit(partsAtServiceFacility.getPart(), conn);

        // TODO: Set Lot to null
    }

    /** Saves an existing partsAtServiceFacility to the database */
    private void update(PartsAtServiceFacility partsAtServiceFacility, Connection conn) throws Exception {
        // use a prepared statement to prevent sql injection
        // TODO: Correct Update Statement
        //      Date: 3/4/2009 - Brady White
        PreparedStatement stmt = conn.prepareStatement("UPDATE parts_at_service_facility SET actual_price=?, list_price=?  WHERE serviceFacility_id=? AND physical_car_id=?");
        try {
            // Get PartsAtServiceFacility Attributes and add them to the statement
            // TODO: Assign Correct SQL PartsAtServiceFacility Attributes
            //      Date: 3/4/2009 - Brady White
            stmt.setString(1, partsAtServiceFacility.getServiceFacilityId());
            stmt.setString(2, partsAtServiceFacility.getPartId());
            stmt.execute();

            // PartsAtServiceFacility is clean!
            partsAtServiceFacility.setDirty(false);
        } finally {
            stmt.close();  // make sure to close the prepared statement
        }
    }

    /** Inserts a new partsAtServiceFacility into the database */
    private void insert(PartsAtServiceFacility partsAtServiceFacility, Connection conn) throws Exception {
        // TODO: Correct Insert Statment
        //      Date: 3/4/2009 - Brady White
        PreparedStatement stmt = conn.prepareStatement("INSERT INTO parts_at_service_facility (serviceFacility_id, physical_car_id, actual_price, list_price) VALUES (?, ?, ?, ?)");
        try {
            // Set PartsAtServiceFacility Attributes
            // TODO: Assign Correct PartsAtServiceFacility Attributes
            //      Date: 3/4/2009 - Brady White
            stmt.setString(1, partsAtServiceFacility.getServiceFacilityId());
            stmt.setString(2, partsAtServiceFacility.getPartId());
            stmt.execute();

            partsAtServiceFacility.setObjectAlreadyInDB(true); // now in DB
            partsAtServiceFacility.setDirty(false); // object is clean
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stmt.close(); // close the prepared statement
        }
    }

    /////////////////////////////////////////////////
    ///   DELETE methods
    /** We do not support deleting of business objects in this application */
    public void delete(PartsAtServiceFacility partsAtServiceFacility) throws DataException {
        throw new RuntimeException("Nice try. The delete function is not supported in this application.");
    }

    ////////////////////////////////////////////////
    ///   SEARCH methods

}
